/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dsmsforkjoin;

import java.util.ArrayList;
import tuplegenerator.Tuple;

/**
 *
 *
 */
public class FJoin<T extends Tuple> {
    
    private ForkList<IForkQueue<T>, T> flist = null;
    
    public FJoin(ForkList<IForkQueue<T>, T> flist) {
        this.flist = flist;
    }
    
    public ArrayList<Tuple> generate() {
        int n = flist.listCount();
        int ind[] = new int[n];
        
        IForkQueue<T> sq = new SortedListQueue<T>();
        sq.setSize(5);
        
        ForkListSimpleQueue<T> flsq = (ForkListSimpleQueue<T>)flist;
        ArrayList<Tuple> tples = new ArrayList<Tuple>();
        
        for (int i=0; i<n; i++) {
        	T item = flsq.getQueue(i).getItem(ind[i]++);
            sq.addItem(item);
        }
        
        while (!sq.isEmpty()) {
            Tuple st = sq.removeHead();
            tples.add(st);
            
            //System.out.println(st.toString());
            int i = st.getIndex();
            if (flsq.getQueue(i-1).getSize() > ind[i-1]) {
                sq.addItem(flsq.getQueue(i-1).getItem(ind[i-1]++));
            }
        }
        
        return tples;
    }

    public ForkList<IForkQueue<T>, T> getFlist() {
        return flist;
    }

    public void setFlist(ForkList<IForkQueue<T>, T> flist) {
        this.flist = flist;
    }
    
    
    
}
